package org.huangrui.javase;

import java.util.*;

/**
 * @Author hr
 * @Create 2025-11-01 20:34
 **/
public class T07ListRemoveDuplicates {
    /**
     * list去除重复元素你能想到几个方法，校招题
     * 有些面试官不让你用API，要求纯手写
     * @param args
     */
    public static void main(String[] args) {
        // m1();
        // m2();
        // m3();
        m4();
        // m5();
    }
    /**
     * 双for循环对比，通过下标获得值，外层循环和内层循环对比，值相同去重复
     */
    private static void m5(){
        List<Integer> initList = Arrays.asList(1, 2, 2, 3, 4, 4, 4, 4, 55, 55, 66, 77, 77, 88);
        ArrayList<Integer> newList = new ArrayList<>(initList);
        for (int i = 0; i < newList.size()-1; i++) {
            for (int j = newList.size()-1; j > i; j--) {
                if (newList.get(i).equals(newList.get(j))){
                    newList.remove(j);
                }
            }
        }
        newList.forEach(v -> System.out.print(v + " "));
    }
    /**
     * 循环坐标去除重复，类似双指针，按照值找到下标，
     * 如果下标不同，表示有重复需要删除
     */
    private static void m4(){
        List<Integer> initList = Arrays.asList(1, 2, 2, 3, 4, 4, 4, 4, 55, 55, 66, 77, 77, 88);
        ArrayList<Integer> srcList = new ArrayList<>(initList);
        ArrayList<Integer> newList = new ArrayList<>(initList);
        System.out.println(newList.indexOf(1));
        System.out.println(newList.lastIndexOf(88));
        System.out.println(newList.size());
        System.out.println();
        for (Integer iter : srcList) {
            if (newList.indexOf(iter) != newList.lastIndexOf(iter)) {
                newList.remove(newList.lastIndexOf(iter));
            }
        }
        newList.forEach(v -> System.out.print(v + " "));
    }
    /**
     * Stream流式计算
     */
    private static void m3(){
        List<Integer> srcList = Arrays.asList(2, 2, 1, 3, 4, 4, 4, 4, 55, 55, 66, 77, 77, 88);
        srcList.stream().distinct().forEach(v -> System.out.print(v +" "));
    }    /**
     * HashSet 或 LinkedHashSet 去重
     */
    private static void m2(){
        List<Integer> srcList = Arrays.asList(2, 2, 1, 3, 4, 4, 4, 4, 55, 55, 66, 77, 77, 88);
        ArrayList<Integer> newList = new ArrayList<>(new HashSet<>(srcList));
        newList.forEach(v-> System.out.print(v +" "));
        System.out.println();
        System.out.println();
        newList = new ArrayList<>(new LinkedHashSet<>(srcList));
        newList.forEach(v-> System.out.print(v +" "));
    }
    /**
     * for循环遍历判断是否含有，没有就添加到newList中
     */
    private static void m1() {
        List<Integer> initList = Arrays.asList(1, 2, 2, 3, 4, 4, 4, 4, 55, 55, 66, 77, 77, 88);
        ArrayList<Integer> newList = new ArrayList<>();
        for (int i = 0; i < initList.size(); i++) {
            Integer tempVal = initList.get(i);
            if (!newList.contains(tempVal)){
                newList.add(tempVal);
            }
        }
        System.out.println(newList);
    }
}
